<template>
  <el-select
    ref="select"
    v-model="defaultValue"
    :clearable="false"
    :multiple="multiple"
    :placeholder="placeholder"
    :disabled="disabled"
    :value-key="defaultProps.value"
    :filter-method="filterMethod"
    @remove-tag="removeTag"
    @visible-change="visibleChange"
    @clear="clear"
  >
    <template #empty>
      <div class="sc-table-select__table" :style="{ width: tableWidth + 'px' }" v-loading="loading">
        <div class="sc-table-select__header">
          <slot name="header" :form="formData" :submit="formSubmit"></slot>
        </div>

        <el-table
          ref="table"
          style="font-size: 14px"
          :data="tableData"
          :height="245"
          :highlight-current-row="!multiple"
          @row-click="rowClick"
          @select="select"
          @select-all="selectAll"
          reserve-selection
        >
          <el-table-column v-if="multiple" type="selection" width="45"></el-table-column>
          <el-table-column v-else type="index" width="45">
            <template #default="scope"
              ><span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span></template
            >
          </el-table-column>
          <slot></slot>
        </el-table>

        <div class="sc-table-select__page">
          <el-pagination
            small
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="currentChange"
          ></el-pagination>
        </div>
      </div>
    </template>
  </el-select>
</template>

<script>
import config from "./tableSelect";

export default {
  props: {
    value: { type: [String, Number, Array, Object], default: "" },
    // Not Request，all Table Data
    tabularData: { type: Array, default: () => [] },
    // 数据value是否以逗号隔开
    isDataJoin: { type: Boolean, default: true },

    params: { type: Object, default: () => {} },
    placeholder: { type: String, default: "请选择" },
    multiple: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    tableWidth: { type: Number, default: 200 },

    // 合并默认配置
    props: { type: Object, default: () => {} },
    // 是否需要数据过滤
    isNeedDataFilter: { type: Boolean, default: true },
    filterParam: { type: Object, default: () => {} },
  },
  data() {
    return {
      loading: false,
      keyword: null,
      defaultValue: [],
      tableData: [],
      pageSize: config.pageSize,
      total: 0,
      currentPage: 1,
      defaultProps: {
        label: config.props.label,
        value: config.props.value,
        page: config.request.page,
        pageSize: config.request.pageSize,
        keyword: config.request.keyword,
      },
      formData: {},
      tabularMap: {},
    };
  },
  watch: {
    value: {
      handler() {
        this.$nextTick(() => {
          if (!this.isDataJoin) {
            if (this.multiple) {
              this.defaultValue = this.value || [];
            } else {
              this.defaultValue = this.value;
            }
          } else {
            // 多选
            if (this.multiple) {
              this.defaultValue = Array.isArray(this.value) ? this.value : this.value ? this.value.split(",") : [];
              this.defaultValue = (this.defaultValue || []).map((item) => {
                return { [this.defaultProps.value]: item };
              });
            } else {
              this.defaultValue = this.value ? { [this.defaultProps.value]: this.value } : "";
            }
          }
          this.findLabel();
        });
      },
      deep: true,
      immediate: true,
    },
    tabularData: {
      handler(val) {
        this.$nextTick(() => {
          val?.forEach((item) => {
            this.tabularMap[item[this.defaultProps.value]] = item[this.defaultProps.label];
          });
          this.findLabel();
        });
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // bug，在这不能使用nextTick
    this.defaultProps = Object.assign(this.defaultProps, this.props);
  },
  methods: {
    // 表格显示隐藏回调
    visibleChange(visible) {
      if (visible) {
        this.currentPage = 1;
        this.keyword = null;
        this.formData = {};
        this.getData();
      } else {
        this.findLabel();
      }
    },
    // 获取表格数据
    getData() {
      // this.tableData = deepClone(this.tabularData)
      this.total = this.tabularData.length;
      this.tableData = this.tabularData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
      if (Object.keys(this.formData).length > 0) {
        const input = this.formData[this.defaultProps.label];
        if (input) {
          const arr = this.tabularData.filter((item) => {
            return String(item[this.defaultProps.label]).toLowerCase().match(input);
          });
          this.total = arr.length;
          this.tableData = arr.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        }
      }
      // 表格默认赋值
      this.$nextTick(() => {
        if (this.multiple) {
          this.defaultValue.forEach((row) => {
            const arr = this.tableData.filter((item) => item[this.defaultProps.value] === row[this.defaultProps.value]);
            if (arr.length > 0) {
              this.$refs.table.toggleRowSelection(arr[0], true);
            }
          });
        } else {
          const arr = this.tableData.filter(
            (item) => item[this.defaultProps.value] === this.defaultValue[this.defaultProps.value]
          );
          this.$refs.table.setCurrentRow(arr[0]);
        }
        this.$refs.table.$el.querySelector(".el-table__body-wrapper").scrollTop = 0;
      });
    },
    // 插糟表单提交
    formSubmit() {
      this.currentPage = 1;
      this.keyword = null;
      this.getData();
    },
    // 分页刷新表格
    currentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    // 赋值
    findLabel() {
      this.$nextTick(() => {
        if (this.multiple) {
          this.$refs.select.selected.forEach((item) => {
            item.currentLabel = this.tabularMap[item.value[this.defaultProps.value]];
          });
        } else {
          this.$refs.select.selectedLabel = this.tabularMap[this.defaultValue[this.defaultProps.value]] || "";
        }
      });
    },
    // 表格勾选事件
    select(rows, row) {
      var isSelect = rows.length && rows.indexOf(row) !== -1; // tip：row属于rows里的数据，同一地址，所以可判断
      if (isSelect) {
        this.defaultValue.push(row);
        if (this.isNeedDataFilter) {
          var flag = false;
          if (+row[this.filterParam.key] == this.filterParam.value) {
            flag = true;
          }
        }
        this.dataFilter(flag);
      } else {
        console.log(this.defaultValue);
        this.defaultValue.splice(this.defaultValue.findIndex(item => item[this.defaultProps.value] === row[this.defaultProps.value]), 1)
      }
      if (this.isDataJoin) {
        this.defaultValue = this.defaultValue.map((item) => item[this.defaultProps.value]).join(",");
      }
      this.findLabel();
      this.$emit("input", this.defaultValue);
      this.$emit("change", this.defaultValue);
    },
    // 表格全选事件
    selectAll(rows) {
      var isAllSelect = rows.length > 0;
      if (isAllSelect) {
        var flag = false;
        rows.forEach((row) => {
          var isHas = this.defaultValue.find((item) => item[this.defaultProps.value] === row[this.defaultProps.value]);
          if (!isHas) {
            this.defaultValue.push(row);
            if (this.isNeedDataFilter) {
              if (+row[this.filterParam.key] == this.filterParam.value) {
                flag = true;
              }
            }
          }
        });
        this.dataFilter(flag);
      } else {
        this.tableData.forEach((row) => {
          const index = this.defaultValue.findIndex(
            (item) => item[this.defaultProps.value] === row[this.defaultProps.value]
          );
          if (index !== -1) {
            this.defaultValue.splice(index, 1);
          }
        });
      }
      if (this.isDataJoin) {
        this.defaultValue = this.defaultValue.map((item) => item[this.defaultProps.value]).join(",");
      }
      this.findLabel();
      this.$emit("input", this.defaultValue);
      this.$emit("change", this.defaultValue);
    },
    async rowClick(row) {
      if (this.multiple) {
        // 处理多选点击行
        this.$refs.table.toggleRowSelection(row);
        const isSelect = this.defaultValue.filter((item) => item.bizid === row.bizid).length !== 0;
        let oldDefaultValue = [...this.defaultValue] || [];
        if (isSelect) oldDefaultValue = this.defaultValue.filter((item) => item.bizid !== row.bizid);
        if (!isSelect) oldDefaultValue.push(row);
        this.select(oldDefaultValue || [], row);
      } else {
        this.defaultValue = "";
        this.$emit("input", this.defaultValue);
        this.$emit("change", this.defaultValue);
        await this.$nextTick();
        this.defaultValue = row;
        if (this.isDataJoin) {
          this.defaultValue = row[this.defaultProps.value];
        }
        this.$refs.select.blur();
        this.findLabel();
        this.$emit("input", this.defaultValue);
        this.$emit("change", this.defaultValue);
      }
    },
    // tags删除后回调
    removeTag(tag) {
      var row = this.findRowByKey(tag[this.defaultProps.value]);
      this.$refs.table.toggleRowSelection(row, false);
      if (this.isDataJoin) {
        this.defaultValue = this.defaultValue.map((item) => item[this.defaultProps.value]).join(",");
      }
      this.$emit("input", this.defaultValue);
      this.$emit("change", this.defaultValue);
    },
    // 清空后的回调
    clear() {
      this.$emit("input", this.defaultValue);
      this.$emit("change", this.defaultValue);
    },
    // 关键值查询表格数据行
    findRowByKey(value) {
      return this.tableData.find((item) => item[this.defaultProps.value] === value);
    },
    filterMethod(keyword) {
      if (!keyword) {
        this.keyword = null;
        return false;
      }
      this.keyword = keyword;
      this.getData();
    },
    // 触发select隐藏
    blur() {
      this.$refs.select.blur();
    },
    // 触发select显示
    focus() {
      this.$refs.select.focus();
    },
    dataFilter(flag) {
      if (this.multiple && this.isNeedDataFilter) {
        this.defaultValue = this.defaultValue.filter((v) => {
          const tepArr = this.tabularData.filter((i) => {
            if (flag) {
              return i[this.filterParam.key] != this.filterParam.value;
            } else {
              return i[this.filterParam.key] == this.filterParam.value;
            }
          });
          const tepVal = tepArr.find((t) => t[this.defaultProps.value] === v[this.defaultProps.value]);
          if (tepVal) {
            this.$refs.table.toggleRowSelection(tepVal, false);
            return false;
          }
          return true;
        });
      }
    },
  },
};
</script>

<style scoped>
.sc-table-select__table {
  padding: 12px;
}
.sc-table-select__page {
  padding-top: 12px;
}
</style>
